#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "rtmp.h"

#define BUF_SIZE (1024*1024)

static int flv_read_one_tag(FILE *fp,char buf[],int max)
{
    if(fp == NULL) return -1;

    int size = 0;
    long offset = ftell(fp);
    unsigned char tagHeader[11];
    int tagDataLen = 0;
    static int seq = 0;

    if(offset==0)
    {
	size = fread(buf,1,13,fp);
	if(buf[0]!='F' || buf[1] != 'L' || buf[2] != 'V')
	{
	    printf("file is not flv format!\n");
	    return -1;
	}
	fread(tagHeader,1,11,fp);
	tagDataLen = (tagHeader[1]<<16) + (tagHeader[2]<<8) + (tagHeader[3]);
	printf("[%d] tagSize = %d\n",seq++,tagDataLen);
	memcpy(buf+size,tagHeader,11);
	size += 11;
	size += fread(buf+size,1,tagDataLen+4,fp);
    }
    else
    {
	size = fread(tagHeader,1,11,fp);
	if(size < 11)
	{
	    printf("@@@ file is end!,last size = %d\n",size);
	    return -1;
	}
	tagDataLen = (tagHeader[1]<<16) + (tagHeader[2]<<8) + (tagHeader[3]);
	printf("[%d] tagSize = %d\n",seq++,tagDataLen);
	memcpy(buf,tagHeader,11);
	size += fread(buf+size,1,tagDataLen+4,fp);
    }

    return size;
}

// rtmp api success return TRUE
//
int main(int argc,char*argv[])
{
    int ret = 0;
    //char *streamingUrl = "rtmp://pili-publish.wmatrix.net/robcat-live/xdbc3110?e=1482896943&token=r54ZPMr3i4OFSrsTmOfyF7bf3VHle-Vq9r3ckgUR:wzBuz4Yve3jD2Xm-bOB35Nd5sRY="; // qiniu
    char *streamingUrl = "rtmp://pili-publish.wmatrix.net/robcat-live/xipcam-test-008?e=1557822522&token=r54ZPMr3i4OFSrsTmOfyF7bf3VHle-Vq9r3ckgUR:Xr3TjHXDt7ohwHBc_vF_3FeWdiI="; // qiniu

    RTMP *rh = NULL;

    rh = RTMP_Alloc();
    RTMP_Init(rh);

    ret = RTMP_SetupURL(rh,streamingUrl);
    if(ret <= 0)
    {
	printf("setup url %s fail,ret = %d\n",streamingUrl,ret);
	goto end;
    }

    RTMP_EnableWrite(rh);

    ret = RTMP_Connect(rh,NULL);
    if(ret <= 0)
    {
	printf("connect rtmp fail,ret = %d\n",ret);
	goto end;
    }
    ret = RTMP_ConnectStream(rh,0);
    if(ret <= 0)
    {
	printf("connect stream fail ret = %d\n",ret);
	goto end;
    }

    // start read or write
    // RTMP_Read / RTMP_Write
    FILE *fp = fopen("demo.flv","rb");
    char buf[BUF_SIZE];
    int size = 0;

    if(fp==NULL)
    {
	printf("open flv file fail!\n");
	goto end;
    }

    do{
	// TODO: get flv data to buf from file
	size = flv_read_one_tag(fp,buf,sizeof(buf));
	if(size <= 0)
	{
	    printf("flv read tag fail,size = %d\n",size);
	    break;
	}
	ret = RTMP_Write(rh,buf,size);
	printf("rtmp write size = %d,ret = %d\n",size,ret);
	usleep(10000);
    } while(ret>0);

    fclose(fp);
    RTMP_Close(rh);

end:
    RTMP_Free(rh);

    return ret;
}

